package com.vertx.web;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class UrlVerticle extends AbstractVerticle {

	private int num = 0;

	public static void main(String[] args) {

		Runner.runExample(UrlVerticle.class);

	}

	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		HttpServer server = vertx.createHttpServer();

		Router router = Router.router(vertx);

		router.route().handler(BodyHandler.create());


		router.route("/test/addNum").handler(req -> {

			System.out.println("num:" + ++num);
			req.response()
					.putHeader("content-type", "application/json")
					.end(new JsonObject().put("type", "/test/addNum").toString());
		});

		//传统模式  /test?name=xxx&age=yyy
		router.route("/test").handler(req -> {

			String name = req.request().getParam("name");
			String age = req.request().getParam("age");
			System.out.println("name:" + name);
			System.out.println("age:" + age);
			req.response()
					.putHeader("content-type", "application/json")
					.end(new JsonObject().put("name", name).put("age", age).put("type", "/test?name=xxx&age=yyy").toString());
		});

		//Rest模式  /test/xxx/yyy
		router.route("/test/:name/:age").handler(req -> {

			String name = req.request().getParam("name");
			System.out.println("rest--->name:" + name);
			req.response()
					.putHeader("content-type", "application/json")
					.end(new JsonObject().put("name", name).put("type", "/test/:name/:age").toString());
		});

		//form-data格式
		router.route("/test/body").handler(req -> {

			JsonObject j = req.getBodyAsJson();
			String headerValue = req.request().getHeader("Content-Type");
			System.out.println("headerValue:" + headerValue);
			req.response()
					.putHeader("content-type", "application/json")
					.end(j.toString());
		});
		server.requestHandler(router).listen(8080);

	}
}
